//
//  PullDownRefreshControl.swift
//  sinaWeibo
//
//  Created by hjun on 16/3/29.
//  Copyright © 2016年 hjun. All rights reserved.
//

import UIKit


//MARK: 动态添加下拉刷新控件属性。方便下拉刷新使用

private var pullDownRefreshContolKey = "pullDownRefreshContolKey"
extension UIScrollView{
    
    ///使用运行时
    private var pullDownRefreshControl: PullDownRefreshControl{
        
        get{///来对象身上根据KEY去找东西
            if let refreshControl = objc_getAssociatedObject(self, &pullDownRefreshContolKey) as? PullDownRefreshControl {
                return refreshControl
            }else {
                //在对象身上没有找到东西
                let refreshControl = PullDownRefreshControl()
                
                ///添加到scrollView上面
                self.addSubview(refreshControl)
                
                ///将refreshControl关联到self,会调用setter方法
                
                self.pullDownRefreshControl = refreshControl
                
                return refreshControl
            }
        }
        
        set{
            
            objc_setAssociatedObject(self, &pullDownRefreshContolKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            
        }
    }
    
    //MARK: 对外添加三个公开的方法
    
    ///添加开始刷新的闭包
    func addPullDownRefreshHandle(handle:() ->()){
        
        pullDownRefreshControl.pullDownRefreshHandle = handle
        
    }
    
    
    ///开始刷新
    
    func startRefrshing(){
        
        pullDownRefreshControl.startRefreshing()
    }
    
    ///结束刷新 加载到数据后调用
    
    func endRefreshing(){
        
        pullDownRefreshControl.endRedreshing()
    }
    
}




private let PullDownRefreshControlHeight: CGFloat = 60

///刷新控件的三种状态
enum PullDownRefreshControlStatus: Int {
    ///下拉刷新 箭头朝下
    case Normal
    /// 箭头朝上释放刷新
    case PullToRefresh
    ///正在刷新 风火轮旋转
    case Refreshing
    
}

class PullDownRefreshControl: UIView{
    
    //MARK:属性
    private  weak var scrollView: UIScrollView!
    
    ///刷新控件开始刷新的回调
    
    var pullDownRefreshHandle: (() ->())?
    
    ///记录上一次状态
    private var lastStatus: PullDownRefreshControlStatus = .Normal
    
    ///当前的刷新状态 默认是Normal
    var currentStatus: PullDownRefreshControlStatus = .Normal{
        
        didSet{
            
            switch currentStatus{
                
            case .Normal:
                wheel.layer.removeAllAnimations()
                wheel.hidden = true
                arrow.hidden = false
                labelRefresh.text = "下拉刷新"
                UIView.animateWithDuration(HJDefaultDuration, animations: { () -> Void in
                    
                    self.arrow.transform = CGAffineTransformIdentity
                })
                if lastStatus == .Refreshing{
                    
                    UIView.animateWithDuration(HJDefaultDuration, animations: { () -> Void in
                        
                        self.scrollView.contentInset.top -= PullDownRefreshControlHeight
                    })
                }
            case .PullToRefresh:
                labelRefresh.text = "释放刷新"
                UIView.animateWithDuration(HJDefaultDuration, animations: { () -> Void in
                    
                    self.arrow.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                    
                })
            case .Refreshing:
                labelRefresh.text = "正在刷新..."
                arrow.hidden = true
                wheel.hidden = false
                
                let rotation = CABasicAnimation(keyPath: "transform.rotation")
                rotation.toValue = 2 * M_PI
                rotation.repeatCount = MAXFLOAT
                rotation.duration = 0.5
                
                wheel.layer.addAnimation(rotation, forKey: "rotation")
                ///
                UIView.animateWithDuration(HJDefaultDuration, animations: { () -> Void in
                    
                    self.scrollView.contentInset.top += PullDownRefreshControlHeight
                    
                    }, completion: { (_) -> Void in
                        
                        self.pullDownRefreshHandle?()
                        
                })
            }
            lastStatus = currentStatus
        }
    }
    
    //MARK: 公开方法
    ///开始刷新
    func startRefreshing(){
        
        currentStatus = .Refreshing
    }
    
    
    ///结束刷新
    func endRedreshing(){
        
        currentStatus = .Normal
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: -PullDownRefreshControlHeight, width: UIScreen.width, height: PullDownRefreshControlHeight)
        
        super.init(frame: newFrame)
        prepareUI()
    }
    
    
    
    private func  prepareUI(){
        
        ///添加子控件
        addSubview(arrow)
        addSubview(wheel)
        addSubview(labelRefresh)
        
        ///隐藏风火轮
        wheel.hidden = true
        
        ///添加约束
        arrow.translatesAutoresizingMaskIntoConstraints = false
        wheel.translatesAutoresizingMaskIntoConstraints = false
        labelRefresh.translatesAutoresizingMaskIntoConstraints = false
        
        ///箭头
        
        addConstraint( NSLayoutConstraint(item: arrow, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -30))
        
        addConstraint( NSLayoutConstraint(item: arrow, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        ///风火轮
        
        addConstraint( NSLayoutConstraint(item: wheel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: arrow, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -30))
        
        addConstraint( NSLayoutConstraint(item: wheel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: arrow, attribute:NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        ///label
        
        addConstraint( NSLayoutConstraint(item: labelRefresh, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: arrow, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10))
        
        addConstraint( NSLayoutConstraint(item: labelRefresh, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: arrow, attribute:NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        
    }
    ///移除KVO
    
    deinit {
        
        scrollView.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    ///view即将被添加到父控件上面 当调用addsubView触发
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        ///监听tableview的contentOffset
        
        if let scrollView = newSuperview as? UIScrollView{
            
            self.scrollView = scrollView
            ///kvo监听
            
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New,NSKeyValueObservingOptions.Old], context: nil)
            
            
        }
        
    }
    
    ///当KVO监听对象属性发生改变时调用
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if scrollView.dragging{
            
            if currentStatus == .PullToRefresh && scrollView.contentOffset.y > -scrollView.contentInset.top - PullDownRefreshControlHeight{
                
                HJPrint(msg: "切换到normal")
                currentStatus = .Normal
            }else if currentStatus == .Normal && scrollView.contentOffset.y < -scrollView.contentInset.top - PullDownRefreshControlHeight{
                HJPrint(msg: "切换到PullToRefresh")
                currentStatus = .PullToRefresh
                
            }else if currentStatus == .PullToRefresh{
                
                HJPrint(msg: "切换到Refreshing")
                currentStatus = .Refreshing
                
            }
        }
    }
        
    //MARK: 懒加载
    
    ///箭头
    
    private lazy var arrow: UIImageView = UIImageView(image: UIImage(named:"tableview_pull_refresh"))
    
    ///轮子
    private lazy var wheel: UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    
    ///label
    private lazy var labelRefresh: UILabel = {
        
        let label = UILabel()
        
        label.textColor = UIColor.darkGrayColor()
        
        label.text = "下拉刷新"
        
        label.font = UIFont.systemFontOfSize(HJPictureViewFontSize)
        
        
        return label
    }()
    
}

